/**
 * Created by levy on 2016/12/22.
 */
import {ajax} from  '../util'
import {locale} from './budget-const'
import _ from 'lodash'

/**
 * 修改了原对象
 * @param item
 * @returns {*}
 */
function count(item) {

    const add = (...keys) => (
        keys.reduce((sum, key) => _.add(sum, parseFloat(item[key]) || 0), 0)
    )

    item.s1 = add('FMONTH1', 'FMONTH2', 'FMONTH3')
    item.s2 = add('FMONTH4', 'FMONTH5', 'FMONTH6')
    item.s3 = add('FMONTH7', 'FMONTH8', 'FMONTH9')
    item.s4 = add('FMONTH10', 'FMONTH11', 'FMONTH12')
    item.thisYear = add('FACTUAL', 'FEXPECT')

    let arr = [item.s1, item.s2, item.s3, item.s4]
    item.nextYear = arr.reduce((sum, v) => _.add(sum, v), 0)

    return item
}


function fetch(url, params) {
    let options = {
        contentType: 'application/json',
        timeout : 15000
    }
    options.url = url

    if (params) {
       for (let key in params) options[key] = params[key]
    }

    return new Promise((resolve, reject) => {
        ajax(options, data => resolve(data), err => {console.error(err); reject(err) })
    })
}

const budget = {
    name: 'budget',
    initialState: {
        isDataReady: false,
        isStructReady: false,
        tableLoading: false,
        loading: true,
        module: {
            PAGEDIMENSIONS: [],
            ROWDIMENSIONS:[],
            COLDIMENSIONS: []
        }, // 模块信息, 页维/行维/列维都在这里
        fixedDims: [], // 固定维度, 也即年/期间/版本
        fixedDimItems: [], // 固定维度选项
        dims: [], // 动态维度
        dimItems: [], // 动态维度的选项
        reportStruct: [], // 报表结构
        reportData: [] // 报表数据
    },
    sagas: {
    *fetchBudgetModule(action, {call, put, update}) {
        // yield update({loading: true})

        try {
            var response = yield call(fetch, `/system/api/v1/modules/multilanguage/BUDGET_MODULES/${action.moduleId}`)
        } catch (e) {
            yield update({loading: false})
            alert ('服务器正忙')
            return
        }

        if (!_.isEmpty(response.payload)) {

            let payload = response.payload.filter(item => item.LOCALE == locale)
            payload = payload[0]

            let {
                PAGEDIMENSIONS,
                ROWDIMENSIONS,
                COLDIMENSIONS
            } = payload

            payload.PAGEDIMENSIONS = JSON.parse(PAGEDIMENSIONS)
            payload.ROWDIMENSIONS = JSON.parse(ROWDIMENSIONS)
            payload.COLDIMENSIONS = JSON.parse(COLDIMENSIONS)

            yield update({module: payload})
        }
        else
            yield console.error('fetchBudgetModule: Budget Module null')
    },
    /**
     * 渲染table时要用到 
     */
    *fetchDimTitles(action, {call, update}) {
        try {
            var resp = yield call(fetch, `/system/api/v1/modules/multilanguage/BUDGET_DIM?size=9999`);
        } catch (e) {
            yield update({loading: false})
            alert ('服务器正忙')
            return
        }

        let data = resp.payload.content.filter(item => item.LOCALE == locale)

        yield update({dimTitles: data})
    },
    /**
     * 一个接口同时获取本页面的维度及维度值
     */
    *fetchDims(action, {call, put, update}) {
        yield update({loading: true})

        // let payload = response.payload.content.filter(item => item.LOCALE == locale)
        try {
            var resp = yield call(fetch, `/system/api/v2/budget-combinations/${action.moduleId}/pageDimensions?locale=${locale}`);
        } catch (e) {
            yield update({loading: false})
            alert ('服务器正忙')
            return
        }

        let payload = resp.payload

        if(typeof payload != 'string') {
            let dimItems = payload.dimItems.reduce((prev, curr) => {
                let itemArr = prev[curr.FDIM_ID]
                if (!itemArr) {
                    itemArr = []
                    prev[curr.FDIM_ID] = itemArr
                }

                itemArr.push({
                    label: curr.FNAME,
                    value: curr.ID
                })

                return prev
            }, {})

            let dims = payload.dims.map(dim => (
                {label: dim.FNAME, ID: dim.ID, FCODE: dim.FCODE}
            ))

            yield update({dimItems: dimItems, dims: dims, loading: false})
        }
        else {
            // yield put({ type: 'LOAD_BUDGET_MODULE.FAILURE', response })
            yield update({loading: false})
            yield console.error(payload)
        }
    },
    *fetchFixedDimItems(action, {call, update, put}) {
        try {
            var resp = yield call(fetch, `/system/api/v2/budget-combinations/year_period_version?locale=${locale}`)
        } catch (e) {
            yield update({loading: false})
            alert ('服务器正忙')
            return
        }
        let payload = resp.payload

        if (payload['dims']) {
            let dimItems = payload.dimItems.reduce((prev, curr) => {
                let itemArr = prev[curr.FDIM_ID]
                if (!itemArr) {
                    itemArr = []
                    prev[curr.FDIM_ID] = itemArr
                }

                itemArr.push({
                    label: curr.FNAME,
                    value: curr.ID
                })

                return prev
            }, {})

            // update 前面一定要有yield
            yield update({fixedDims: payload.dims, fixedDimItems: dimItems})
        }
        else
            yield console.error(payload)
    },
    *fetchReportData(action, {call, put, update}) {
        yield update({tableLoading: true})

        try {
            var resp = yield call(fetch,
                `/system/api/v2/budget-combinations/${action.moduleId}/query;keys=${action.keys};values=${action.values}?locale=${locale}`,
                {type: 'PUT', data: action.body})
        } catch (e) {
            yield update({tableLoading: false})
            alert ('服务器正忙')
            return
        }


        let data = resp.payload.data.map(item => count(item))

        yield update({reportData: data, isDataReady: !!data.length, tableLoading: false})
    },
    *fetchReportStruct(action, {call, put, update}) {
        try {
            var resp = yield call(fetch,
                `/system/api/v2/budget-combinations/${action.moduleId};keys=${action.keys};values=${action.values}?locale=${locale}`)
        } catch (e) {
            yield update({loading: false})
            alert ('服务器正忙')
            return
        }

        if (typeof resp.payload == 'string') {
            yield alert(resp.payload)
            yield update({isStructReady: false})
            return
        }

        let data = resp.payload.data

        yield update({reportStruct: data, isStructReady: !!data.length})
    },
    *showReport(action, {update}) {
        yield update({isDataReady: action.show, isStructReady: action.show})
    }
  }
}

export default budget
